<?php

class text_helper {

		/* 16进制转2进制 */
	function hex2bin($str)
	{
		$len = strlen($str);
		return pack("H" . $len, $str);
	}


		/* 补上小数为 */
	function round( $val , $l ) {
		$val= round($val , $l);
		$ex= explode(".", $val);
		if( count($ex)==1 ) {
			$val.=".";
			for($i=0;$i<$l;$i++) {
				$val.="0";
			}
		} else if( strlen($ex[1])<$l ) {
			for($i=0;$i<$l-strlen($ex[1]);$i++) {
				$val.="0";
			}
		}
		return $val;
	}



		//取得标题gb2312字串
	function title_substrGB2312( $str, $len , $ifmax_pre="…") {
		$ret= "";
		if(strlen($str)>$len) {
			$ret= text_helper::substr_gb2312($str,0,$len).$ifmax_pre;
		} else {
			$ret= $str;
		}
		return $ret;
	}

		//截取gb2312字串
	function substr_gb2312($str,$start,$len=null) {
		$totlelength = strlen($str);
		//特例情况
		if ($len == null) $len = $totlelength;
		if ($len ==0) return "";
		if ($len >= $totlelength && $start == 0 ) return $str;
		if ($start > $totlelength) return "";
		//分析$start
		if ($start < 0 ){  //$start<0时,转化为$start>0时的定位.
			if ( abs($start) >= $totlelength ) $start = 0;
			else $start = $totlelength - abs($start);
		}

		//确定起始位置,当起始位拆分某汉字时,返回值包含此汉字.
		if ($start > 0) {
			$i = $start-1;
			$flag = -1;
			while ($i >= 0) {
				if ( ord(substr($str,$i,1)) > 160) {
					$flag = -1*$flag;
				}
				else break;
				$i--;
			}
			if($flag==1) {
				$start = $start - 1;
				$len++;  //保证不位移.
			}
		}
		$str = substr($str,$start);//截除字符串$str的$start位前的字符
		$totlelength = strlen($str);

		//确定结束位置,当结束位拆分某汉字时,返回值不包含此汉字.
		if ($len<0) $len = $totlelength - abs($len);
		if ($len <= 0) return "";
		$i=min($len,$totlelength);
		$i--;
		$flag = -1;
		while ($i >= 0){
			if (ord(substr($str,$i,1))>160){
				$flag=-1*$flag;
			}
			else break;
			$i--;
		}
		if($flag == 1)
			$len=$len-1;
		$subit=substr($str,0,$len);
		return $subit;
	}
}
